package com.zj.interceptor;

import com.zj.config.JWTUtil;
import com.zj.enums.BizCodeEnum;
import com.zj.result.R;
import com.zj.utils.CommonUtils;
import io.jsonwebtoken.Claims;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * @author 自己的名字
 * @version 1.0.0
 * @ClassName LoginInterceptor
 * @Description
 * @createTime 2024年12月17日 21:21
 */
public class LoginInterceptor implements HandlerInterceptor {

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        if (HttpMethod.OPTIONS.toString().equalsIgnoreCase(request.getMethod())){
            response.setStatus(HttpStatus.NO_CONTENT.value());
        }

        String accessToken = request.getParameter("token");
        if (accessToken != null && accessToken.length() > 0){
            accessToken = request.getHeader("token");
        }
        if (accessToken != null){
            Claims claims = JWTUtil.checkJwt(accessToken);
            if (claims == null){
                CommonUtils.sendJsonMessage(response, R.data(BizCodeEnum.ERROR.getCode(),"no login"));
                return false;
            }
            long accountNo = Long.parseLong(claims.get("account_no").toString());
            return true;
        }
        return false;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}
